package com.miku.blog.utils;

import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author shkstart
 * @create ${}YEAR-05-26 0:44
 */
public class BeanCopyUtils {

    public static <T> T copyObjectByType(Object source, Class<T> targetClass) {
        T target = null;
        try {
            target = targetClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, target);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return target;
    }

    public static <T> List<T> copyListByType(List<?> sourceList, Class<T> targetClass) {
        List<T> targetList = sourceList.stream()
                .map(source -> copyObjectByType(source, targetClass))
                .collect(Collectors.toList());
        return targetList;
    }


    public static void copyProperties(Object target,Object... sources){
        if (Objects.isNull(sources) || sources.length <= 0){
            return;
        }
        for (Object source : sources) {
            BeanUtils.copyProperties(source,target);
        }
    }


}
